import re
import os
import subprocess
import traceback
import logging
log = logging.getLogger('log')

def build_command():
    """构造命令参数列表"""
    java_home = os.getenv("JAVA_HOME", "/usr/lib/jvm/java-11-openjdk")
    base_cmd = [
#        "cd", "/root/worker/mmj_java_src/key_manage_bankend_system/mmj_java_src","&&",
        os.path.join(java_home, "bin", "java"),
        "-cp", "out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar",
        "-Djava.library.path=/usr/lib",
        "JCECrypto"
    ]
    return base_cmd

def extract_base64_key(output):
    match = re.search(r"密钥生成成功\(base64\)：\s*([A-Za-z0-9+/=]+)", output)
    result = match.group(1) if match else None
    if result is None:
        match = re.search(r"加密成功\(base64\)：\s*([A-Za-z0-9+/=]+)", output)
        result = match.group(1) if match else None
    return result


BASE_CMD = build_command()

import subprocess
from typing import List, Tuple, Optional, Any

def command_run(commands: List[Tuple[str, dict]]) -> Tuple[int, Any]:
    """
    执行一系列命令并返回结果
    
    Args:
        commands: 命令列表，每个元素是(命令类型, 额外参数)的元组
    
    Returns:
        元组(状态码, 结果或错误信息):
        - (0, 结果): 执行成功
        - (错误码, 错误信息): 执行失败
    """
    last_error = (1, "未执行任何命令")  # 默认错误状态
    
    # for cmd_type, extra in commands:
    if True:
        try:
            # 构建命令
            # cmd = build_command(cmd_type, extra)
            # if not cmd:
            #     error_msg = f"无法为类型 {cmd_type} 构建命令"
            #     print(f"警告: {error_msg}")
            #     log.error("{traceback.format_exc()}")
            #     last_error = (-1, error_msg)
            #     continue
                
            log.info(f"\n执行命令: {' '.join(commands)}")
            
            # 执行命令
            result = subprocess.run(
                commands,
                cwd="./mmj_java_src",
                capture_output=True,
                text=True,
                check=True,  # 如果返回码非零则抛出异常
                timeout=30  # 设置超时时间
            )
            
            # 返回第一个成功的命令结果
            stdout = result.stdout
            stderr = result.stderr
            print("comand origin return: ", stdout, stderr)
            if stdout is not None:
                return (0, stdout.strip())
            else:
                return (-1, stderr)
            
        except Exception as e:
            error_msg = f"执行命令时发生意外错误: {str(e)}"
            print(error_msg)
            log.error(f"{traceback.format_exc()}")
            last_error = (-1, error_msg)
    
    # 所有命令都执行失败，返回最后一个错误
    return last_error

def _command_run(commands):
    for cmd_type, extra in commands:
        cmd = build_command(cmd_type, extra)
        print(f"\n执行命令: {' '.join(cmd)}")
        try:
            result = subprocess.run(cmd, capture_output=True, text=True)
            return(result.stdout or result.stderr)
        except Exception as e:
            print(f"执行失败: {str(e)}")
            return None

def command_encrypt(cert, data):
    commands = BASE_CMD+ [
            "encrypt",
            "-cert", cert,
            "-data", data
        ]
    status, result = command_run(commands)
    if status == 0:
        result = extract_base64_key(result)
    return status, result   

def command_genkey(key_type):
    commands = BASE_CMD + [
        "genkey",
        "-type", key_type
    ]
    status, result = command_run(commands)
    print("command genkey: ", status, result)
    if status == 0:
        result = extract_base64_key(result)
    return status, result   

def command_derive_key(diver, rootkey):
    commands = BASE_CMD + [ 
        "genkey",
        "-type", "DERIVED_SM4",
        "-diver", diver,
        "-rootkey", rootkey
    ]
    status, result = command_run(commands)
    if status == 0:
        result = extract_base64_key(result)
    return status, result   


# 使用示例
if __name__ == "__main__":
# echo "1. 加密数据示例："
# echo "$JAVA_HOME/bin/java -cp \"out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" -Djava.library.path=/usr/lib JCECrypto encrypt -cert \"MIIBoTCCAUWgAwIBAgIIRcqC+k8GG5YwDAYIKoEcz1UBg3UFADAhMQswCQYDVQQGEwJDTjESMBAGA1UEAwwJ5qC56K+B5LmmMCAXDTIzMTAxMDE2MDAwMFoYDzIwNTMxMDAyMT6wMDAwWjAhMQswCQYDVQQGEwJDTjESMBAGA1UEAwwJ5qC56K+B5LmmMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEuU1w2nF9qRirc78jRFZLZ/RVQLUMXUi9IdofqQTgAVQFXayqewvCYZkBKXdOWyXjl6goUwBcp7AHBdQIFtfQU6NjMGEwHwYDVR0jBBgwFoAUmNcVyA4Q/Vfrrm1CUSBOumpHPk4wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAc4wHQYDVR0OBBYEFJjXFcgOEP1X665tQlEgTrpqRz5OMAwGCCqBHM9VAYN1BQADSAAwRQIgdquZAwZCXLtUZPLFds9d2mDRYhYqVt0JVEaNYwxNcM8CIQDudMwc2f5JU9GI/BMyq0El5ww2Bx6GQM2Iq2AxBsptcQ==\" -data \"000102030405060708090A0B0C0D0E0F\""
# echo

# echo "2. 生成 SM4 密钥："
# echo "$JAVA_HOME/bin/java -cp \"out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" -Djava.library.path=/usr/lib JCECrypto genkey -type SM4"
# echo

# echo "3. 生成 SM1 密钥："
# echo "$JAVA_HOME/bin/java -cp \"out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" -Djava.library.path=/usr/lib JCECrypto genkey -type SM1"
# echo

# echo "4. 生成 SM4 分散密钥："
# echo "$JAVA_HOME/bin/java -cp \"out:CDF_JMJ_API-1.4.jar:CDFJCE-2.1.2.jar:CDF_JMJ_JNI-1.4.jar:CDFSoft-2.2.jar\" -Djava.library.path=/usr/lib JCECrypto genkey -type DERIVED_SM4 -diver aaaaaaaa -rootkey C11FFA9E4874FCE466C74C6E8476685C"
# echo
    try:
        cert = "MIIBoTCCAUWgAwIBAgIIRcqC+k8GG5YwDAYIKoEcz1UBg3UFADAhMQswCQYDVQQGEwJDTjESMBAGA1UEAwwJ5qC56K+B5LmmMCAXDTIzMTAxMDE2MDAwMFoYDzIwNTMxMDAyMT6wMDA0WjAhMQswCQYDVQQGEwJDTjESMBAGA1UEAwwJ5qC56K+B5LmmMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEuU1w2nF9qRirc78jRFZLZ/RVQLUMXUi9IdofqQTgAVQFXayqewvCYZkBKXdOWyXjl6goUwBcp7AHBdQIFtfQU6NjMGEwHwYDVR0jBBgwFoAUmNcVyA4Q/Vfrrm1CUSBOumpHPk4wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAc4wHQYDVR0OBBYEFJjXFcgOEP1X665tQlEgTrpqRz5OMAwGCCqBHM9VAYN1BQADSAAwRQIgdquZAwZCXLtUZPLFds9d2mDRYhYqVt0JVEaNYwxNcM8CIQDudMwc2f5JU9GI/BMyq0El5ww2Bx6GQM2Iq2AxBsptcQ=="
        data = "AAECAwQFBgcICQoLDA0ODw=="
        r = command_encrypt(cert, data)
        print("加密结果:", r)
        r = command_genkey("SM4")
        print("生成的 SM4 密钥:", r)
        r = command_genkey("SM1")
        print("生成的 SM1 密钥:", r)
        derive = "YWFhYWFhYWE=" 
        rootkey = "wxH/pk50/OZmx0xuhHZoXA=="
        r = command_derive_key(derive, rootkey)
        print("生成的 SM4 分散密钥:", r)
    except Exception as e:
        traceback.print_exc()
        print("错误:", str(e))
